package com.fipl.taksar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.android.c2dm.C2DMBaseReceiver;

public class C2DMReceiver extends C2DMBaseReceiver {
	
	private static final int NOTIFICATION_ID=2;
	private static final int REQUEST_CODE=1;
	private String regId=null;
	
	public C2DMReceiver() {
		// Email address currently not used by the C2DM Messaging framework
		super("dummy@google.com");
	}

	@Override
	public void onRegistered(Context context, String registrationId)
			throws java.io.IOException {
		// The registrationId should be send to your applicatioin server.
		// We just log it to the LogCat view
		// We will copy it from there
		Log.e("C2DM", "Registration ID arrived: Fantastic!!!");
		Log.e("C2DM", registrationId);
		setRegId(registrationId);
		((GlobalData)context.getApplicationContext()).setRegistrationID(registrationId);
		
	};
	
	public void setRegId(String regId) {
		this.regId = regId;
	}

	public String getRegId() {
		return regId;
	}

	@Override
	protected void onMessage(Context context, Intent intent) {
		try{
			
			Log.e("C2DM", "Message: Fantastic!!!");
			// Extract the payload from the message
			Bundle extras = intent.getExtras();
			if (extras != null) {
				Log.d("System out", "" + extras.get("payload"));
				Log.d("System out", "from " + extras.get("from"));
				String message =  (String) extras.get("message");
				Log.d("System out", "Message " + message);
				displayNotification(message);
				System.out.println(extras.get("payload"));
				// Now do something smart based on the information
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			Log.d("C2DM", "Error in getting payload");
		}
		
	}

	@Override 
	public void onError(Context context, String errorId) {
		Log.e("C2DM", "Error occured!!!");
	}
	
	public void displayNotification(String msg){
	NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	Notification notification = new Notification(R.drawable.tkmeicon, msg, System.currentTimeMillis());

	// The PendingIntent will launch activity if the user selects this notification
	PendingIntent contentIntent = PendingIntent.getActivity(this, REQUEST_CODE, new Intent(this, C2DMReceiver.class), 0);
	notification.setLatestEventInfo(this, "Teksar Alert", msg, contentIntent);
	manager.notify(NOTIFICATION_ID, notification);
	}
	
}
